use prost::Message;
use std::sync::Arc;
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, Mutex};
use tracing::info;

use crate::error::War3Error;
use crate::proto::{ClientListUpdate, DataForward, MessageType, Notification, War3Message};

/// 发送消息任务
#[derive(Debug)]
pub struct SendMessage {
    pub message: War3Message,
    pub response_tx: Option<tokio::sync::oneshot::Sender<Result<(), War3Error>>>,
}

/// 客户端会话
/// 使用split后的读写半部分，避免锁竞争
pub struct ClientSession {
    #[allow(dead_code)]
    war3_ip: String,
    read_half: Arc<Mutex<ReadHalf<TcpStream>>>,
    write_half: Arc<Mutex<WriteHalf<TcpStream>>>,
    channel_queue_tx: mpsc::Sender<TcpStream>,
    channel_queue_rx: Arc<Mutex<mpsc::Receiver<TcpStream>>>,
    send_queue: mpsc::Sender<SendMessage>,
}

impl ClientSession {
    pub fn new(
        war3_ip: String,
        stream: TcpStream,
    ) -> (Self, mpsc::Receiver<SendMessage>) {
        let (tx, rx) = mpsc::channel(10);
        let (send_tx, send_rx) = mpsc::channel(100);
        
        // 使用tokio::io::split将TCP流分割为读写两半，彻底消除锁竞争
        let (read_half, write_half) = tokio::io::split(stream);
        
        (
            Self {
                war3_ip,
                read_half: Arc::new(Mutex::new(read_half)),
                write_half: Arc::new(Mutex::new(write_half)),
                channel_queue_tx: tx,
                channel_queue_rx: Arc::new(Mutex::new(rx)),
                send_queue: send_tx,
            },
            send_rx,
        )
    }

    /// 获取 War3 IP
    pub fn war3_ip(&self) -> &str {
        &self.war3_ip
    }

    /// 获取读半部分
    pub fn read_half(&self) -> Arc<Mutex<ReadHalf<TcpStream>>> {
        Arc::clone(&self.read_half)
    }
    
    /// 获取写半部分
    pub fn write_half(&self) -> Arc<Mutex<WriteHalf<TcpStream>>> {
        Arc::clone(&self.write_half)
    }

    /// 获取通道队列接收器
    pub fn channel_queue_rx(&self) -> Arc<Mutex<mpsc::Receiver<TcpStream>>> {
        Arc::clone(&self.channel_queue_rx)
    }

    /// 获取通道队列发送器
    pub fn channel_queue_tx(&self) -> mpsc::Sender<TcpStream> {
        self.channel_queue_tx.clone()
    }

    /// 发送通知消息
    pub async fn send_notification(&self) -> Result<(), War3Error> {
        let notification = Notification {};
        let message = War3Message {
            r#type: MessageType::Notification as i32,
            source_ip: String::new(),
            target_ip: String::new(),
            payload: notification.encode_to_vec(),
        };

        // 不需要等待客户端响应，直接发送消息（与 Java/Go 版本保持一致）
        self.send_queue
            .send(SendMessage {
                message,
                response_tx: None, // 不等待响应
            })
            .await
            .map_err(|_| War3Error::ConnectionClosed)?;

        Ok(())
    }

    /// 更新客户端列表
    pub async fn update_client_list(&self, client_ips: Vec<String>) -> Result<(), War3Error> {
        let update = ClientListUpdate {
            client_ips: client_ips.clone(),
        };
        let message = War3Message {
            r#type: MessageType::ClientListUpdate as i32,
            source_ip: String::new(),
            target_ip: String::new(),
            payload: update.encode_to_vec(),
        };

        info!(
            "update_client_list,Before send_queue, client_list={:?}",
            client_ips
        );
        
        // 不需要等待客户端响应，直接发送消息
        self.send_queue
            .send(SendMessage {
                message,
                response_tx: None, // 不需要响应
            })
            .await
            .map_err(|_| War3Error::ConnectionClosed)?;

        info!("update_client_list,Message sent successfully");
        Ok(())
    }

    /// 转发数据
    pub async fn forward_data(
        &self,
        from_ip: String,
        target_ip: String,
        data: Vec<u8>,
    ) -> Result<(), War3Error> {
        let data_forward = DataForward {
            from_ip: from_ip.clone(),
            data,
        };
        let message = War3Message {
            r#type: MessageType::DataForward as i32,
            source_ip: from_ip,
            target_ip,
            payload: data_forward.encode_to_vec(),
        };

        // 不需要等待客户端响应，直接发送消息
        self.send_queue
            .send(SendMessage {
                message,
                response_tx: None, // 不需要响应
            })
            .await
            .map_err(|_| War3Error::ConnectionClosed)?;

        Ok(())
    }
}
